<?php
function randomstr($len = 6)
{
	$string = 'ABCDEFGHIJKLMNOPQRSTUVWZYZabcdefghijklmnopqrstuvwxyz0123456789';
	$string = str_shuffle($string);
	return substr($string, 0, $len);
}

function randomnum($len = 6)
{
	$string = '123456789';
	$string = str_shuffle($string);
	return substr($string, 0, $len);
}

/**
 * CURL GET方式抓取内容
 * @param string $url The input string.
 * @return string 
 *
 */
function http_get($url)
{
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_TIMEOUT, 3);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070803 Firefox/1.5.0.12');
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	$result = curl_exec($ch);
	if (curl_errno($ch)) $result = '';
	curl_close($ch);
	return $result;
}
/**
 * CURL POST方式抓取内容
 * @param string $url The input string.
 * @param string $data The input string.
 * @return string 
 *
 */
function http_post($url, $data = '')
{
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_TIMEOUT, 3);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070803 Firefox/1.5.0.12');
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	$result = curl_exec($ch);
	if (curl_errno($ch)) $result = '';
	curl_close($ch);
	return $result;
}
/**
 * 输出JSON接口数据
 * 
 * @param array $data 主体数据
 * @param integer $code 代码编号
 * @return string json
 *
 */
function response_json($data = NULL, $code = 0, $message = 'OK', $jsonp = false)
{
	if (!defined('IN_CI')) header('content-type:application/json;charset=utf8');
	$array = array(
		'code' => $code,
		'msg' => $message,
		'data' => $data,
	);
	//if (empty($data)) unset($array['data']);
	echo  !$jsonp ? json_encode($array, JSON_UNESCAPED_UNICODE) : ($_GET['callback'] . '(' . json_encode($array, JSON_UNESCAPED_UNICODE) . ')');
	exit;
}
/**
 * 输出带分页统计JSON接口数据
 * 
 * @param array $data 主体数据
 * @param integer $code 代码编号
 * @return string json
 *
 */
function response_listJson($data = NULL, $count = 0, $jsonp = false)
{
	if (!defined('IN_CI')) header('content-type:application/json;charset=utf8');
	$array = array(
		'code' => $count > 0 ? "0" : "101",
		'msg' => $count > 0 ? 'OK' : "无数据",
		'data' => $data,
		'count' => $count
	);
	if (empty($data)) unset($array['data']);
	echo  !$jsonp ? json_encode($array, JSON_UNESCAPED_UNICODE) : ($_GET['callback'] . '(' . json_encode($array, JSON_UNESCAPED_UNICODE) . ')');
	exit;
}
/**
 *  获取用户ID
 * 
 */
function getip()
{
	$onlineip = '';
	if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$onlineip = getenv('HTTP_CLIENT_IP');
	} elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$onlineip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$onlineip = getenv('REMOTE_ADDR');
	} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$onlineip = $_SERVER['REMOTE_ADDR'];
	}
	if (strpos($onlineip, ',') != false) {
		$ipr = explode(",", $onlineip);
		$onlineip = $ipr[0];
	}
	return $onlineip;
}
/**
 *  检查权限
 *
 */
function check_login()
{
	@session_start();
	if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_auth'])) {
		redirect('login');
		exit;
	}
	$CI = &get_instance();
	$row = $CI->db->where(array('user_id' => intval($_SESSION['user_id'])))->get('member')->row_array();
	if ($row['user_auth'] != $_SESSION['user_auth'] || empty($_SESSION['user_auth'])) {
		redirect('login');
		exit;
	}
	return (int) $_SESSION['user_id'];
}

/*移动端判断*/
function isMobile()
{
	// 如果有HTTP_X_WAP_PROFILE则一定是移动设备
	if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
		return true;
	}
	// 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
	if (isset($_SERVER['HTTP_VIA'])) {
		// 找不到为flase,否则为true
		return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
	}
	// 脑残法，判断手机发送的客户端标志,兼容性有待提高
	if (isset($_SERVER['HTTP_USER_AGENT'])) {
		$clientkeywords = array(
			'nokia',
			'sony',
			'ericsson',
			'mot',
			'samsung',
			'htc',
			'sgh',
			'lg',
			'sharp',
			'sie-',
			'philips',
			'panasonic',
			'alcatel',
			'lenovo',
			'iphone',
			'ipod',
			'blackberry',
			'meizu',
			'android',
			'netfront',
			'symbian',
			'ucweb',
			'windowsce',
			'palm',
			'operamini',
			'operamobi',
			'openwave',
			'nexusone',
			'cldc',
			'midp',
			'wap',
			'mobile'
		);
		// 从HTTP_USER_AGENT中查找手机浏览器的关键字
		if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
			return true;
		}
	}
	// 协议法，因为有可能不准确，放到最后判断
	if (isset($_SERVER['HTTP_ACCEPT'])) {
		// 如果只支持wml并且不支持html那一定是移动设备
		// 如果支持wml和html但是wml在html之前则是移动设备
		if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
			return true;
		}
	}
	return false;
}

function check_account($ret = false, $jump = 'login')
{
	@session_start();
	if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_auth'])) {
		if ($ret) return false;
		redirect($jump);
		exit;
	}
	$CI = &get_instance();
	$row = $CI->db->where(array('user_id' => intval($_SESSION['user_id'])))->get('member')->row_array();
	if ($row['user_auth'] != $_SESSION['user_auth'] || empty($_SESSION['user_auth'])) {
		if ($ret) return false;
		redirect($jump);
		exit;
	}
	return (int) $_SESSION['user_id'];
}

function public_vars()
{
	$CI = &get_instance();
	$CI->load->model(array(
		'level_model', 'member_model', 'region_model', 'member_address_model'
	));

	$user_id = (int) $_SESSION['user_id'];
	//获取用户基本信息
	$user = $CI->member_model->get_by_id($user_id);
	//获取所有等级数据
	$level = $CI->level_model->result_maps($CI->level_model->result_all("where 1", "order by level_sort asc"));
	//获取上级ID
	if ($user['level_up']) {
		$user['parent'] = $CI->member_model->get_by_id($user['level_up'], 'user_id,username,mobile,fullname');
	} else {
		$user['parent'] = array();
	}
	//用户地址数据
	if ($user['address_id'] > 0) {
		$user['address'] = $CI->member_address_model->get_by_id($user['address_id']);
	} else {
		$user['address'] = array();
	}
	//用户等级
	$user['level'] = $CI->level_model->get_by_id($user['level_id']);

	//获取商城系统用户数据
	$json = api_user_info('user_id', $user_id);
	$shop_info = $json['result'] ? $json['data'] : array();
	//用户购物券
	$pay_points = $shop_info['pay_points'] ? $shop_info['pay_points'] : 0;
	$user['integral'] = (int) $pay_points;

	$data = array(
		'user' => $user,
		'shop_info' => $shop_info,
		'level' => $level
	);

	$CI->load->vars($data);
}


function create_page_links($base_url, $total, $per_page, $cur_page = 1, $prefix, $suffix)
{
	$CI = &get_instance();
	$CI->load->library('pagination');
	$config                     = array();
	$config['base_url']         = $base_url;
	$config['total_rows']       = intval($total);
	$config['per_page']         = intval($per_page);
	$config['cur_page']         = intval($cur_page);
	$config['prefix']           = $prefix;
	$config['suffix']           = $suffix;
	$config['first_link']       = FALSE;
	$config['last_link']        = FALSE;
	$config['cur_tag_open']     = ' <span class="current">';
	$config['cur_tag_close']    = '</span>';
	$config['use_page_numbers'] = 5;
	$config['prev_link']        = '<';
	$config['next_link']        = '>';
	$config['display_numbs']	= TRUE;
	$config['use_page_numbers'] = TRUE;
	$config['reuse_query_string'] = TRUE;
	$CI->pagination->initialize($config);
	$create_links = $CI->pagination->create_links();
	/*
    if($create_links)
    {
        $create_links = '<div class="pagination">'.$create_links.'</div>';
    }*/
	$CI->vars['num_pages']    = $CI->pagination->num_pages;
	return $create_links;
}


function thumb($filename, $width, $height)
{
	return base_url('/picture/show/' . $filename) . '?size=' . $width . 'x' . $height;
}

function original($filename)
{
	list($hash_file) = explode('.', $filename);
	return base_url('/uploads/' . implode('/', str_split(substr($hash_file, 0, 15), 5)) . '/' . $filename);
}

function order_sn($uid = 0)
{
	$uid = sprintf('%011d', $uid);
	return date('ymd') . $uid . substr(time(), -5) . substr(microtime(), 2, 5);
}

function iframe_msg($msg, $func = '')
{
	return '<script> alert("' . $msg . '"); ' . ($func ? $func : '') . ' </script>';
}

include_once(dirname(__FILE__) . '/TopSdk/TopSdk.php');
/*
* 阿里大于 发送短信
*/
function alidayu_sendsms($mobile, $param, $templateCode, $userid = 0)
{
	$appkey = '23872791';
	$secret = '8e77c7f0a69aca82a49337dbd978ff30';

	$signName = '惠民久久'; //短信签名
	$c = new TopClient;
	$c->appkey = $appkey;
	$c->secretKey = $secret;
	$req = new AlibabaAliqinFcSmsNumSendRequest;
	$req->setExtend($userid); //这里填用户ID
	$req->setSmsType("normal");
	$req->setSmsFreeSignName($signName); //短信签名
	$req->setSmsParam(json_encode($param));
	$req->setRecNum($mobile);
	$req->setSmsTemplateCode($templateCode);
	$resp = $c->execute($req);
	if (isset($resp->code) && $resp->code > 0) {
		return false;
	} else {
		return true;
	}
}

function regSendSms($phone, $code)
{
	include_once 'aliyun-php-sdk-core/Config.php';
	include_once 'Dysmsapi/Request/V20170525/SendSmsRequest.php';
	include_once 'Dysmsapi/Request/V20170525/QuerySendDetailsRequest.php';
	//此处需要替换成自己的AK信息
	$accessKeyId = "LTAIPuwghCzJP0XQ";
	$accessKeySecret = "HVb2WqCeLqcRCjhoWFMempqXnRu0oy";
	//短信API产品名
	$product = "Dysmsapi";
	//短信API产品域名
	$domain = "dysmsapi.aliyuncs.com";
	//暂时不支持多Region
	$region = "cn-hangzhou";
	//初始化访问的acsCleint
	$profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
	DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
	$acsClient = new DefaultAcsClient($profile);

	$request = new Dysmsapi\Request\V20170525\SendSmsRequest;
	//必填-短信接收号码
	$request->setPhoneNumbers($phone);
	//必填-短信签名
	$request->setSignName("易趣网络");
	//必填-短信模板Code
	$request->setTemplateCode("SMS_109490037");
	//选填-假如模板中存在变量需要替换则为必填(JSON格式)
	$request->setTemplateParam("{\"code\":\"" . $code . "\"}");
	//选填-发送短信流水号
	$request->setOutId(time());
	//发起访问请求
	$acsResponse = $acsClient->getAcsResponse($request);
	file_put_contents("/tmp/sms.log", '手机号:' . $phone . '返回：' . var_export($acsResponse, true) . "\t验证码:" . $code . "\r\n", FILE_APPEND);
	if ($acsResponse->Code == 'OK') {
		return true;
	} else {
		return false;
	}
}

function firstCharter($str)
{
	if (empty($str)) return '';
	$fchar = ord($str{
		0});
	if ($fchar >= ord('A') && $fchar <= ord('z')) {
		return strtoupper($str{
			0});
	}
	$s1  = iconv('UTF-8', 'gb2312', $str);
	$s2  = iconv('gb2312', 'UTF-8', $s1);
	$s   = $s2 == $str ? $s1 : $str;
	$asc = ord($s{
		0}) * 256 + ord($s{
		1}) - 65536;
	if ($asc >= -20319 && $asc <= -20284) return 'A';
	if ($asc >= -20283 && $asc <= -19776) return 'B';
	if ($asc >= -19775 && $asc <= -19219) return 'C';
	if ($asc >= -19218 && $asc <= -18711) return 'D';
	if ($asc >= -18710 && $asc <= -18527) return 'E';
	if ($asc >= -18526 && $asc <= -18240) return 'F';
	if ($asc >= -18239 && $asc <= -17923) return 'G';
	if ($asc >= -17922 && $asc <= -17418) return 'H';
	if ($asc >= -17417 && $asc <= -16475) return 'J';
	if ($asc >= -16474 && $asc <= -16213) return 'K';
	if ($asc >= -16212 && $asc <= -15641) return 'L';
	if ($asc >= -15640 && $asc <= -15166) return 'M';
	if ($asc >= -15165 && $asc <= -14923) return 'N';
	if ($asc >= -14922 && $asc <= -14915) return 'O';
	if ($asc >= -14914 && $asc <= -14631) return 'P';
	if ($asc >= -14630 && $asc <= -14150) return 'Q';
	if ($asc >= -14149 && $asc <= -14091) return 'R';
	if ($asc >= -14090 && $asc <= -13319) return 'S';
	if ($asc >= -13318 && $asc <= -12839) return 'T';
	if ($asc >= -12838 && $asc <= -12557) return 'W';
	if ($asc >= -12556 && $asc <= -11848) return 'X';
	if ($asc >= -11847 && $asc <= -11056) return 'Y';
	if ($asc >= -11055 && $asc <= -10247) return 'Z';
	return '';
}
/*
* 身份证识别 $img_value 图像 base64 位值; $side #身份证正反面类型:face/back
*/
function ocr_idcard($img_value, $side = 'face')
{
	if (empty($img_value)) {
		return array();
	}
	$data = array(
		'inputs' => array(
			array(
				'image'     => array(
					'dataType'  => 50,
					'dataValue' => $img_value, //图片二进制数据的base64编码
				),
				'configure' => array(
					'dataType'  => 50,
					'dataValue' => '{"side":"' . $side . '"}',
				)
			),
		),
	);
	$headers = array();
	array_push($headers, "Authorization:APPCODE 457b8c5913cf4255be49c33ae98f93c9");
	//根据API的要求，定义相对应的Content-Type
	array_push($headers, "Content-Type" . ":" . "application/json; charset=UTF-8");

	$url  = 'https://dm-51.data.aliyun.com/rest/160601/ocr/ocr_idcard.json';
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($curl, CURLOPT_FAILONERROR, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_HEADER, true);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($curl, CURLOPT_HEADER, 0);
	curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));

	$json = curl_exec($curl);
	$json = @json_decode($json, true);
	if (!isset($json['outputs'])) {
		return array();
	} else {
		return json_decode($json['outputs'][0]['outputValue']['dataValue'], true);
	}
}
/**
 * 浏览器友好的变量输出
 * @param mixed $var 变量
 * @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
 * @param string $label 标签 默认为空
 * @param boolean $strict 是否严谨 默认为true
 * @return void|string
 */
function dd($var, $echo = true, $label = null, $strict = true)
{
	$label = ($label === null) ? '' : rtrim($label) . ' ';
	if (!$strict) {
		if (ini_get('html_errors')) {
			$output = print_r($var, true);
			$output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
		} else {
			$output = $label . print_r($var, true);
		}
	} else {
		ob_start();
		var_dump($var);
		$output = ob_get_clean();
		if (!extension_loaded('xdebug')) {
			$output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
			$output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
		}
	}
	if ($echo) {
		echo ($output);
		die(1);
	} else {
		return $output;
	}
}

/**
 * 验证token是否正确
 * @param $token
 */
function check_token()
{
	$CI = &get_instance();
	$token = $CI->input->get_post('access_token');
	//    @session_start();
	//    if(!isset($_SESSION['access_token']) || $_SESSION['access_token'] != $token)
	//    {
	//        response_json([],1001,'token已失效');
	//    }
	//
	//    $row = $CI->db->where(array('admin_id'=>intval($_SESSION['admin_id'])))->get('admin')->row_array();
	//    if($row['admin_auth']!=$_SESSION['admin_auth'] || empty($_SESSION['admin_auth']))
	//    {
	//        response_json([],1001,'token已失效');
	//    }
	if (empty($token)) {
		response_json([], 1001, 'token已失效1');
	}
	// 解密token信息
	$CI->load->library('encrypt');
	$users = explode(":", $CI->encrypt->decode($token));
	// 验证token是否已经过期
	if ((time() - $users[2]) > 12000) { // 暂时设置成两个小时过期
		response_json([], 1001, 'token已失效2');
	}
	//dd($users);
	return $users;
}
